﻿#include "stdafx.h"
#include "ThresholdTask.h"
#include <QVBoxLayout>
#include <QRadioButton>
#include <QSpinBox>
#include <QPushButton>
#include <QLabel>

void ThresholdTask::execute(cv::Mat& image) {
	if (useAutoThreshold) {
		// 使用 OTSU 自动阈值
		cv::threshold(image, image, 0, maxValue, cv::THRESH_BINARY | cv::THRESH_OTSU);
	}
	else {
		// 使用手动阈值
		cv::threshold(image, image, manualThreshold, maxValue, cv::THRESH_BINARY);
	}
}

std::string ThresholdTask::getName() const {
	return "阈值化";
}

std::unique_ptr<QDialog> ThresholdTask::getConfigUI() {
	// 创建配置对话框
	auto dialog = std::make_unique<QDialog>();
	QVBoxLayout* layout = new QVBoxLayout(dialog.get());

	// 单选按钮：自动阈值和手动阈值
	QRadioButton* autoRadio = new QRadioButton("自动阈值 (OTSU)");
	QRadioButton* manualRadio = new QRadioButton("手动阈值");
	layout->addWidget(autoRadio);
	layout->addWidget(manualRadio);

	// 手动阈值输入控件
	QLabel* threshLabel = new QLabel("阈值:");
	QSpinBox* threshSpin = new QSpinBox();
	threshSpin->setRange(0, 255);
	threshSpin->setValue(static_cast<int>(manualThreshold));
	layout->addWidget(threshLabel);
	layout->addWidget(threshSpin);
	threshLabel->setVisible(false); // 初始隐藏
	threshSpin->setVisible(false);

	// 动态显示/隐藏手动阈值输入控件
	QObject::connect(manualRadio, &QRadioButton::toggled, [threshLabel, threshSpin](bool checked) {
		threshLabel->setVisible(checked);
		threshSpin->setVisible(checked);
		});

	// 设置初始状态
	if (useAutoThreshold) {
		autoRadio->setChecked(true);
	}
	else {
		manualRadio->setChecked(true);
		threshLabel->setVisible(true);
		threshSpin->setVisible(true);
	}

	// 确认按钮
	QPushButton* okButton = new QPushButton("确认");
	layout->addWidget(okButton);

	// 保存用户选择和输入
	QObject::connect(okButton, &QPushButton::clicked, dialog.get(), [&, autoRadio, threshSpin]() {
		useAutoThreshold = autoRadio->isChecked();
		if (!useAutoThreshold) {
			manualThreshold = threshSpin->value();
		}
		dialog->accept();
		});

	return dialog;
}